package logic

import (
	"context"
	"fmt"

	"gitcode.com/sunsungk9/opensource-demo-cockroachdb-obs-241123/user/internal/svc"
	"gitcode.com/sunsungk9/opensource-demo-cockroachdb-obs-241123/user/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RestoreLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRestoreLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RestoreLogic {
	return &RestoreLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RestoreLogic) Restore(req *types.RestoreUser) (resp *types.Response, err error) {
	// restore from OBS
	restoreFrom := "LATEST"
	if req.Path != "" {
		restoreFrom = req.Path
	}
	fmt.Println("restoreFrom", restoreFrom)
	query := fmt.Sprintf("RESTORE TABLE users FROM '%s' IN 's3://%s?AWS_ENDPOINT=%s&AWS_ACCESS_KEY_ID=%s&AWS_SECRET_ACCESS_KEY=%s'",
		restoreFrom, l.svcCtx.Config.Bucket, l.svcCtx.Config.Endpoint, l.svcCtx.Config.AK, l.svcCtx.Config.SK)
	_, err = l.svcCtx.DB.Exec(query)
	if err != nil {
		return
	}
	resp = new(types.Response)
	resp.Message = "success"
	return
}
